import { Component } from '@angular/core';
import { Router } from '@angular/router';


/**
 * 后台管理视频页列表组件
 */
@Component({
  selector: 'app-videolist',
  templateUrl: './videolist.component.html',
  styleUrls: ['./videolist.component.scss']
})
export class VideolistComponent {
  /**
   * @desc 获取VideoWork表中数据
   */
  VideoList:any[] = [];
  /**
   * @desc 获取isDeleted==true的个数
   */
  deleteCount:number = 0;
  showDelete:boolean = false;
  searchText:string = "";
  
  constructor(private router:Router){
    this.refresh();

    
  }

  /**
   * 
   * 搜索功能
   * - 通过数据Schema表name字段搜索
   * @param ev 监听事件
   */
  search(ev?:Event){
    if(ev){
      if((ev as any).code != "Enter") return
    }
    // where={"isDeleted":false,"name":{"$regex":"${this.searchText}"}}
    let searchParams = `,"title":{"$regex":"${this.searchText}"}`
    this.getVideoList(searchParams)
  }
  /**
   * 调用方法封装
   * @example
   * constructor(){
   * this.refresh();    
   * }
   */
  refresh(){
    this.getVideoList();
    this.getDeleteCount();
  }

  /**
   * 跳转到"/admin-bvideo/videoedit"页面
   * - new一个新对象
   */
  addNewVideo(){
    this.router.navigate(["/admin-bvideo/videoedit"],{
      queryParams:{
        new:true        
      }
    })
  }

  /**
   * 渲染this.showDelete==true时的数据并将!this.showDelete赋值给this.showDelete
   */
  onShowDelete(){
    console.log("onShowDelete")
    this.showDelete=!this.showDelete
    this.refresh()
  }

   /**
   * 跳转到"/admin-bvideo/videolist"页面
   */
  onShowVideo(){
    this.router.navigate(["/admin-bvideo/videolist"],{})
  }


  /**
   * 
   * 获取VideoWork表中数据
   * @param {string} searchParams
   * - 通过参数实现搜索
   * @returns
   * 获取到的列表数据赋值给this.VideoCommentList
   */
  async getVideoList(searchParams=""){
    let url = "http://metapunk.cn:9999/parse/classes/VideoWork?"

    // 拼接排序条件
    let paramsOrder = `order=-countLike`
    url += paramsOrder   

    // 拼接匹配条件
    let paramsWhere
    if(!this.showDelete){
      paramsWhere = `where={"isDeleted":false${searchParams}}`
      url += "&" + paramsWhere
    }else{
      paramsWhere = `where={"isDeleted":true${searchParams}}`
      url += "&" + paramsWhere
    }
    url += '&include=user'

    let result = await fetch(url, {
      "headers": {
        "x-parse-application-id": "dev"
      },
      "body": null,
      "method": "GET",
      "mode": "cors",
      "credentials": "omit"
    });
    let data = await result.json();
    this.VideoList = data.results;
    console.log(this.VideoList);
  }


  /**
   * 获取VideoWork表中字段isDeleted==true数据
   * @returns
   * - 将数据字段isDeleted==true的个数赋值给this.deleteCount
   */
  async getDeleteCount(){
    let url = `http://metapunk.cn:9999/parse/classes/VideoWork?where={"isDeleted":true}&count=1&limit=0`
    url+="&include=user"
    let result = await fetch(url, {
      "headers": {
        "x-parse-application-id": "dev"
      },
      "body": null,
      "method": "GET",
      "mode": "cors",
      "credentials": "omit"
    });
    let data = await result.json();
    this.deleteCount = data.count || 0
  }
  
  /**
   * 
   * 删除对应内存变量
   * @param {object} video 对应数据对象
   * @param {boolean} isRestore 
   * 
   */
  async deleteVideo(video:any,isRestore:boolean=false){
    let isDeleted = true
    if(isRestore==true){
      isDeleted = false
    }
    // 发送HTTP请求，将isDeleted字段更新为true;
    let objectId = video.objectId
    if(objectId){
      let response = await fetch(`http://metapunk.cn:9999/parse/classes/VideoWork/${objectId}`, {
        "headers": {
          "content-type": "text/plain;charset=UTF-8",
          "x-parse-application-id": "dev"
        },
        "body": `{"isDeleted":${isDeleted}}`,
        "method": "PUT",
        "mode": "cors",
        "credentials": "omit"
      });
      let data = await response.json();
      // 成功删除时，HTTP网络请求返回：{"updatedAt":"2023-01-04T08:29:35.195Z"}
      if(data?.updatedAt){
        // 内存变量删除该项
        let idx = this.VideoList.findIndex(item=>item.objectId==video.objectId)
        this.VideoList.splice(idx,1)
        if(isDeleted){
          this.deleteCount ++;
        }else{
          this.deleteCount --;
        }
      }     
    }
    return
  }
  editVideo(video:any){
    console.log(video)
  }
  
  
}
